package com.lf.controller;


import com.lf.model.EbNews;
import com.lf.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    @RequestMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        //1.获取新闻表的第1页数据，每页3条
        List<EbNews> newses = newsService.list(page, pageSize);
        int maxPage = newsService.getMaxPage(pageSize);
        //2.将数据(list)和视图(jsp)返回给spring mvc中央控制
        ModelAndView mv = new ModelAndView();
        //绑定数据
        mv.addObject("newses", newses);//key-value
        mv.addObject("curPage", page);

        mv.addObject("maxPage", maxPage);
        //绑定视图
        mv.setViewName("manage/news");
        return mv;
    }

    @RequestMapping("/to_save")
    public String toSave() {
        return "manage/news-add";
    }

    @RequestMapping("/save_commit")
    public String saveCommit(EbNews ebNews) {

        //补充添加时间
        //获取系统时间
        Date date = new Date();
        //Date  --->  String
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd");
        String timeStr = sdf.format(date);
        //System.out.println("timeStr=="+timeStr);
        ebNews.setEnCreateTime(timeStr);

        if (ebNews.getEnTitle() == null || ebNews.getEnTitle().trim().length() == 0) {
            return "manage/paramError";

        }
        int result = newsService.save(ebNews);
        if (result <= 0) {
            return "manage/error";
        }
        return "manage/manage-result";
    }

    @RequestMapping ("/edit")
    public String edit(Model model, Integer enId){
        EbNews ebNews = newsService.selectByCondition(enId);
        model.addAttribute("ebNews", ebNews);
        return "manage/news-modify";
    }
@RequestMapping("/editSubmit")
    public String editSubmit(EbNews ebNews){
        int result = newsService.updateById(ebNews);
        if (result<=0){
            return "manage/error";
        }
        return "manage/manage-result";
}
    
    @RequestMapping("/delete/{id}")
    public  String delete(@PathVariable("id") Integer id) {
        int result = newsService.delete(id);
        if (result == 0) {
        }
        return "manage/manage-result";
    }
}
